/**
 * @description: 点标绘
 * @author: zhao_sk
 * @date: 2022-04-20 14:24:36
 */
import mapboxgl from 'mapbox-gl';
export class Marker {
	constructor(viewer) {
		this.viewer = viewer;
	}

	/**
	 * 添加标签
	 */
	async add(markerData, callback) {
		const { id, position, text, textColor, textSize, textType, imagePath: image } = markerData;
		if (this.viewer.getLayer(`VGEMarker_${id}`)) {
			return console.error('id already registered');
		}
		if (!this.viewer.hasImage('VGEMarker_default')) {
			this.loadImage('default', pointImg);
		}
		if (image) {
			this.loadImage(id, image);
		}
		this.viewer.addSource(`VGEMarker_${id}`, {
			type: 'geojson',
			data: {
				type: 'Feature',
				geometry: {
					type: 'Point',
					coordinates: position
				},
				properties: {
					title: text
				}
			}
		});
		this.viewer.addLayer({
			id: `VGEMarker_${id}`,
			type: 'symbol',
			source: `VGEMarker_${id}`,
			layout: {
				'icon-image': image ? `VGEMarker_${id}` : 'VGEMarker_default',
				'text-size': +textSize,
				'text-max-width': 20,
				'text-field': '{title}'
			},
			paint: {
				'text-color': textColor,
				'text-translate': [0, textType == 'Top' ? -24 : 24]
			}
		});
	}

	loadImage(id, base64) {
		let image = new Image();
		image.src = base64;
		image.onload = () => {
			this.viewer.addImage(`VGEMarker_${id}`, image);
		};
	}

	/**
	 * 删除标签
	 */
	delete(id) {
		let sid = `VGEMarker_${id}`;
		this.viewer.getLayer(sid) && this.viewer.removeLayer(sid);
		this.viewer.getSource(sid) && this.viewer.removeSource(sid);
		this.viewer.hasImage(sid) && this.viewer.removeImage(sid);
		return true;
	}

	/**
	 * 清除标签
	 */
	clear() {
		this.viewer.getStyle().layers.forEach((item) => {
			if (item.id.includes('VGEMarker_')) {
				this.viewer.removeLayer(item.id);
				this.viewer.removeSource(item.id);
				this.viewer.hasImage(item.id) && this.viewer.removeImage(item.id);
			}
		});
		return true;
	}
}

const pointImg =
	'';
